package stu.xjtu.subject.domain.service.impl;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import stu.xjtu.subject.common.enums.IsDeletedFlagEnum;
import stu.xjtu.subject.domain.convert.SubjectCategoryConverter;
import stu.xjtu.subject.domain.entity.SubjectCategoryBO;
import stu.xjtu.subject.domain.entity.SubjectLabelBO;
import stu.xjtu.subject.domain.service.SubjectCategoryDomainService;
import stu.xjtu.subject.domain.util.CacheUtil;
import stu.xjtu.subject.infra.basic.entity.SubjectCategory;
import stu.xjtu.subject.infra.basic.entity.SubjectLabel;
import stu.xjtu.subject.infra.basic.entity.SubjectMapping;
import stu.xjtu.subject.infra.basic.service.SubjectCategoryService;
import stu.xjtu.subject.infra.basic.service.SubjectLabelService;
import stu.xjtu.subject.infra.basic.service.SubjectMappingService;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SubjectCategoryDomainServiceImpl implements SubjectCategoryDomainService {
    @Resource
    private SubjectCategoryService subjectCategoryService;
    @Resource
    private SubjectMappingService subjectMappingService;
    @Resource
    private SubjectLabelService subjectLabelService;
    @Resource
    private ThreadPoolExecutor labelThreadPool;

    @Resource
    CacheUtil cacheUtil;

    @Override
    public void addSubjectCategory(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory category = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryBO);
        category.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        subjectCategoryService.insert(category);
    }

    @Override
    public List<SubjectCategoryBO> queryCategory(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory category = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryBO);
        category.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryPrimaryCategory(category);
        List<SubjectCategoryBO> boList = SubjectCategoryConverter.INSTANCE.convertToCategoryBOList(subjectCategoryList);
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryController.queryPrimaryCategory.boList:{}",
                    JSON.toJSONString(boList));
        }
        boList.forEach(bo -> {
            Integer subjectCount = subjectCategoryService.querySubjectCount(bo.getId());
            bo.setCount(subjectCount);
        });
        return boList;
    }

    @Override
    public Boolean update(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory category = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryBO);
        int count = subjectCategoryService.update(category);
        return count > 0;
    }

    @Override
    public Boolean delete(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory category = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryBO);
        category.setIsDeleted(IsDeletedFlagEnum.DELETED.getCode());
        int count = subjectCategoryService.update(category);
        return count > 0;
    }

    // CompletableFuture的实现方式
    @Override
    public List<SubjectCategoryBO> queryCategoryAndLabel(SubjectCategoryBO subjectCategoryBO) throws ExecutionException, InterruptedException {
        Long id = subjectCategoryBO.getId();
        String cacheKey = "categoryAndLabel." + subjectCategoryBO.getId();
        List<SubjectCategoryBO> subjectCategoryBOS = cacheUtil.getResult(cacheKey,
                SubjectCategoryBO.class, (key) -> getSubjectCategoryBOS(id));
        return subjectCategoryBOS;
    }

    private List<SubjectCategoryBO> getSubjectCategoryBOS(Long categoryId) {
        SubjectCategory subjectCategory = new SubjectCategory();
        subjectCategory.setParentId(categoryId);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
        List<SubjectCategoryBO> categoryBOList = SubjectCategoryConverter.INSTANCE.convertToCategoryBOList(subjectCategoryList);
        List<CompletableFuture<Map<Long, List<SubjectLabelBO>>>> completableFutureList = categoryBOList.stream().map(category ->
                CompletableFuture.supplyAsync(() -> getLabelBOList(category), labelThreadPool)
        ).collect(Collectors.toList());
        Map<Long, List<SubjectLabelBO>> map = new HashMap<>();
        completableFutureList.forEach(future -> {
            try {
                Map<Long, List<SubjectLabelBO>> resultMap = future.get();
                if (resultMap != null && !resultMap.isEmpty()) {
                    map.putAll(resultMap);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        categoryBOList.forEach(categoryBO -> {
            if (!CollectionUtils.isEmpty(map.get(categoryBO.getId()))) {
                categoryBO.setLabelBOList(map.get(categoryBO.getId()));
            }
        });
        return categoryBOList;
    }

    // 使用FutureTask的方式来实现
    // @Override
    public List<SubjectCategoryBO> queryCategoryAndLabel2(SubjectCategoryBO subjectCategoryBO) throws ExecutionException, InterruptedException {
        SubjectCategory subjectCategory = new SubjectCategory();
        subjectCategory.setParentId(subjectCategoryBO.getParentId());
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
        List<SubjectCategoryBO> categoryBOList = SubjectCategoryConverter.INSTANCE.convertToCategoryBOList(subjectCategoryList);
        List<FutureTask<Map<Long, List<SubjectLabelBO>>>> futureTaskList = new LinkedList<>();
        // 线程池并发调用
        Map<Long, List<SubjectLabelBO>> map = new TreeMap<>();
        categoryBOList.forEach(categoryBO -> {
            FutureTask<Map<Long, List<SubjectLabelBO>>> futureTask = new FutureTask<>(() ->
                    getLabelBOList(categoryBO)
            );
            futureTaskList.add(futureTask);
            labelThreadPool.submit(futureTask);
        });
        for (FutureTask<Map<Long, List<SubjectLabelBO>>> futureTask : futureTaskList) {
            Map<Long, List<SubjectLabelBO>> longListMap = futureTask.get();
            if (CollectionUtils.isEmpty(longListMap)) {
                continue;
            }
            map.putAll(longListMap);
        }
        categoryBOList.forEach(categoryBO -> {
            categoryBO.setLabelBOList(map.get(categoryBO.getLabelBOList()));
        });
        return categoryBOList;
    }

    private Map<Long, List<SubjectLabelBO>> getLabelBOList(SubjectCategoryBO categoryBO) {
        Map<Long, List<SubjectLabelBO>> labelBOMap = new TreeMap<>();
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setCategoryId(categoryBO.getId());
        List<SubjectMapping> subjectMappings = subjectMappingService.queryLabelId(subjectMapping);
        if (CollectionUtils.isEmpty(subjectMappings)) {
            return null;
        }
        List<Long> lableList = subjectMappings.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
        List<SubjectLabel> subjectLableList = subjectLabelService.batchQueryById(lableList);
        List<SubjectLabelBO> lableBoList = new LinkedList<>();
        subjectLableList.forEach(lable -> {
            SubjectLabelBO subjectLabelBO = new SubjectLabelBO();
            subjectLabelBO.setId(lable.getId());
            subjectLabelBO.setLabelName(lable.getLabelName());
            subjectLabelBO.setCategoryId(lable.getCategoryId());
            subjectLabelBO.setSortNum(lable.getSortNum());
            lableBoList.add(subjectLabelBO);
        });
        labelBOMap.put(subjectMapping.getId(), lableBoList);
        return labelBOMap;
    }

    // 没有使用多线程实现
    //@Override
    public List<SubjectCategoryBO> queryCategoryAndLabel1(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory = new SubjectCategory();
        subjectCategory.setParentId(subjectCategoryBO.getParentId());
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
        List<SubjectCategoryBO> categoryBOList = SubjectCategoryConverter.INSTANCE.convertToCategoryBOList(subjectCategoryList);
        categoryBOList.forEach(categoryBO -> {
            SubjectMapping subjectMapping = new SubjectMapping();
            subjectMapping.setCategoryId(categoryBO.getId());
            List<SubjectMapping> subjectMappings = subjectMappingService.queryLabelId(subjectMapping);
            if (CollectionUtils.isEmpty(subjectMappings)) {
                return;
            }
            List<Long> lableList = subjectMappings.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
            List<SubjectLabel> subjectLableList = subjectLabelService.batchQueryById(lableList);
            List<SubjectLabelBO> lableBoList = new LinkedList<>();
            subjectLableList.forEach(lable -> {
                SubjectLabelBO subjectLabelBO = new SubjectLabelBO();
                subjectLabelBO.setId(lable.getId());
                subjectLabelBO.setLabelName(lable.getLabelName());
                subjectLabelBO.setCategoryId(lable.getCategoryId());
                subjectLabelBO.setSortNum(lable.getSortNum());
                lableBoList.add(subjectLabelBO);
            });
            categoryBO.setLabelBOList(lableBoList);
        });
        return categoryBOList;
    }
}
